<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/14
 * Time: 15:42
 */

namespace common\business\company;

use common\business\CommonHelper;
use common\consts\CommonResources;
use common\models\Log;
use Yii;
use common\consts\Consts;
use common\models\Company;
use common\models\kingdee\OrgAdmin;
use common\result\ActionResult;
use yii\db\Exception;
use yii\db\Query;
use yii\helpers\Json;

class CompanyService
{
    /**
     * @param callback|null $writeBackHandler
     * @return ActionResult
     */
    public function sync($writeBackHandler = null) {
        $totalCount = OrgAdmin::find()->count();

        $totalResult = new ActionResult();

        $db = OrgAdmin::getDb();
        $query = (new Query())->from('T_ORG_ADMIN TOA')
            ->leftJoin('T_BD_ORGPROPERTY TBOP', 'TBOP.FID = TOA.FORGPROPERTYID')
            ->leftJoin('T_ORG_LAYERTYPE TOLT', 'TOLT.FID = TOA.FLAYERTYPEID')
            ->leftJoin('T_ORG_ADMIN TOAP', 'TOAP.FID = TOA.FPARENTID')
            ->select([
                'company_name' => 'TOA.FNAME_L2',
                'company_plate' => 'TBOP.FNAME_L2',
                'company_mdm_id' => 'TOA.FBASEDUTY_L2',
                'company_parent_mdm_id' => 'TOAP.FBASEDUTY_L2',
                'company_hr_id' => 'TOA.FNUMBER',
//                'company_finance_id',
//                'company_import_id',
//                'company_market_if',
//                'company_abb',
                'company_ct_start_date' => 'TOA.FSETUPDATE',
                'company_ct_end_date' => 'TOA.FENDUPDATE',
                'company_most_abb' => 'TOA.FSIMPLENAME',
//                'company_longitude',
//                'company_latitude',
//                'company_update_reason',
//                'company_memo',
            ])
//            ->where([
//                'NOT', ['TOLT.FNAME_L2' => '部门']
//            ])
            ->orderBy([
                'TOA.FID' => SORT_ASC,
            ]);

        $offset = 0;
        $pageSize = Consts::DEFAULT_PAGE_SIZE;
        $count = $pageSize;

        while ($count >= $pageSize) {
            $all = $query->offset($offset)->limit($pageSize)->all($db);
            $count = count($all);
            $offset += $pageSize;
            foreach ($all as $itemArr){
                $newCompany = new Company();
                $newCompany->setAttributes($itemArr);

                $companyInDb = Company::findOne([
                    'company_hr_id' => $newCompany->company_hr_id,
                ]);

                $api = new CompanyApiHandler();
                if (!$companyInDb){
                    $totalResult->addSubResult($api->createCompany($newCompany));
                }
                else {
                    $newCompany->company_id = $companyInDb->company_id;
                    $totalResult->addSubResult($api->updateCompany($newCompany, $companyInDb));
                }
                if ($writeBackHandler){
                    $paramArr = [
                        'totalCount' => $totalCount,
                        'finishCount' => $totalResult->total_count,
                        'message' => $totalResult->message,
                    ];
                    call_user_func_array($writeBackHandler, $paramArr);
                }
            }
        }
        return $totalResult;
    }
}